#include "runningselfchecking.h"
#include "ui_runningselfchecking.h"
#include "devicemanagementui.h"

RunningSelfChecking::RunningSelfChecking(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RunningSelfChecking)
{
    ui->setupUi(this);

    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    connected = 0;
    deviceManagement = new DeviceManagement();
    timer = new QTimer();
    InstructionsService *instructions = new InstructionsService();
    cusMsg = new CustomMessageBox();

    /* 休眠100毫秒，让application进入exec循环 */
    connect(timer, &QTimer::timeout, this, [=](){
        qDebug() << "配置文件";
        timer->stop();
        /* 检查配置文件 */
        ui->selfChecking->setText("检测依赖文件...");
        this->sleep(300);
        if(!instructions->configFileDetect()){
            qDebug() << "配置文件不存在";
            /* 弹出错误窗口 */
            cusMsg->show(this, CMsg::CCritical, "致命错误", "配置文件不存在或配置文件结构有误！！\n 请检查配置文件是否存在或检查配置文件格式是否正确");

            this->close();
            QApplication *qapp;
            qapp->quit();
            return;
        }
        else {
            ui->selfChecking->setText("配置文件检查成功！");
            this->sleep(200);
        }


        /* 检查数据库文件 */
        /* 绑定数据库文件定时器 */
        ui->selfChecking->setText("检查数据库文件");
        this->sleep(300);
        if(!instructions->dbFileDetect()){
            ui->selfChecking->setText("数据库文件不存在！");
            this->sleep(200);
            ui->selfChecking->setText("创建数据库中...");
            this->sleep(200);
            ui->selfChecking->setText("数据库创建成功！");
            this->sleep(300);
        }
        else {
            ui->selfChecking->setText("数据库文件检查成功！");
            this->sleep(300);
        }

        /* 检查设备连接情况 */
        /* 绑定设备定时器 */
        QList<QHash<QString,QString>> devicesList = deviceManagement->show();
        for(int i = 0; i < devicesList.size();i ++){
            InstructionsService *instructionsServices = new InstructionsService();
            QString ip = devicesList[i]["ip"];
            int port = devicesList[i]["port"].toInt();
            qDebug() << ip << " " << port;
            cDev.dev.QHashToStruct(devicesList[i]);
            selfChecking = "检测设备 \"" + devicesList[i]["name"] + "\"";
            ui->selfChecking->setText(selfChecking);
            this->sleep(100);
            if(instructionsServices->establishConnection(ip,port)){
                selfChecking = "设备 \"" + devicesList[i]["name"] + "\" 连接成功!";
                ui->selfChecking->setText(selfChecking);
                instructionsServices->sendChecking(devicesList[i]["id"]);
                this->sleep(300);
                cDev.dev.status = "已连接";
                connected++;

            }else{
                selfChecking = "设备 \"" + devicesList[i]["name"] + "\" 连接超时";
                ui->selfChecking->setText(selfChecking);
                this->sleep(300);
            }
            cDev.msg = instructionsServices->ziJianData;
            if(cDev.msg.size() != 0){
                if(cDev.msg[2].contains("成功"))
                    cDev.dev.status = "已连接";
                else if(cDev.msg[2].contains("运行") && !cDev.msg[2].contains("不运行"))
                    cDev.dev.status = "运行中";
                else
                    cDev.dev.status = "故障";
            }
            /* 初始化 */
            instructionsServices->ziJianData.clear();
            cDev.instructionsService = instructionsServices;
            connectDeviceInfo.append(cDev);

            /* 链接关闭 */
            if(cDev.instructionsService->m_socketClient->isConnected()){
                cDev.instructionsService->m_socketClient->closeSocket();
            }
        }
        selfChecking = "共有 " + QString::number(connected) + " 台设备连接成功";
        ui->selfChecking->setText(selfChecking);
        this->sleep(300);

        /* 所有设备自检成功，进入主界面 */
        ui->selfChecking->setText("自检完毕，正在进入主界面...");
        m = new MainWindow();
        //        qDebug() << "selfChecking" << connectDeviceInfo.size();

        this->sleep(300);
        m->show();
        this->close();
    });
    timer->start(100);

}
RunningSelfChecking::~RunningSelfChecking()
{
    delete ui;
}

void RunningSelfChecking::sleep(int msec){
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
